import 'dart:convert';

import 'package:get/get.dart';
import 'package:juming_test/action/domain_action.dart';
import 'package:juming_test/model/domain/domain_filter_condition_model.dart';
import 'package:juming_test/model/domain/domain_filter_item_model.dart';
import 'package:juming_test/model/domain/domain_filter_option_model.dart';
import 'package:juming_test/model/domain/domain_filter_section_model.dart';

class DomainFilterViewModel extends GetxController {
  // 全部配置数据
  final Rx<List<DomainFilterSectionModel>> sections = Rx([]);
  // 存储筛选条件
  final Rx<Map<String, dynamic>> filterData = Rx({});
  // 筛选条件展示
  final Rx<List<DomainFilterConditionModel>> conditionItems = Rx([]);

  @override
  Future<void> onReady() async {
    super.onReady();
    // 获取页面基础配置数据
    await _getSections();
  }

  // MARK: - 公共方法

  /// 重置筛选条件
  void resetFilterData() {
    filterData.value = {};
    _updateSectionAndConditionByFilterData('');
  }

  /// 更新筛选条件
  void updateFilterData(String key, String value) {
    if (value == '-1') {
      filterData.value.remove(key);
    } else {
      filterData.value[key] = value;
    }
    _updateSectionAndConditionByFilterData(key);
  }

  /// 删除筛选条目
  void deleteFilterItem(int index) {
    if (index < conditionItems.value.length) {
      DomainFilterConditionModel item = conditionItems.value[index];
      // 删除filterData中的key
      _removeRelatedKeys(item.key);
    }
    _updateSectionAndConditionByFilterData('');
  }

  /// 获取页面传参数据
  String getParamsDataString() {
    Map<String, dynamic> params = filterData.value;
    for (var section in sections.value) {
      for (var item in section.children) {
        // 带复选框的单输入框，如果输入框没有值，则删除相关key
        if (item.type == DomainFilterItemType.singleInput) {
          if (params[item.key] == null) {
            for (var option in item.options) {
              params.remove(option.key);
            }
          }
        }
        // 如果衍生条目没有值，则删除key
        if (item.derivativeValue.isNotEmpty &&
            params[item.key] == item.derivativeValue) {
          bool hasValue = false;
          for (var derivativeItem in item.derivativeItems) {
            if (derivativeItem.inputValue1.isNotEmpty ||
                derivativeItem.inputValue2.isNotEmpty) {
              hasValue = true;
            }
            for (var option in derivativeItem.options) {
              if (option.isSelected) {
                hasValue = true;
              }
            }
          }
          if (!hasValue) {
            params.remove(item.key);
          }
        }
      }
    }
    // 如果value没有值（无限），则删除key
    List<String> keysToRemove = [];
    for (var key in params.keys) {
      if (params[key] == '') {
        keysToRemove.add(key);
      }
    }
    for (var key in keysToRemove) {
      params.remove(key);
    }

    if (params.isEmpty) {
      return '';
    }
    final dataStr = Uri.encodeComponent(jsonEncode(params));
    return dataStr;
  }

  /// 通过页面传参filterData更新数据源
  void updateByData(Map<String, dynamic> data) {
    filterData.value = data;
    _updateSectionAndConditionByFilterData('update');
  }

  // MARK: - 私有方法

  /// 删除与指定key相关的所有键
  void _removeRelatedKeys(String key) {
    filterData.value.remove(key);
    if (!key.contains('_1')) {
      filterData.value.remove('${key}_1');
    }
    if (!key.contains('_2')) {
      filterData.value.remove('${key}_2');
    }
  }

  /// 添加条件项
  void _addConditionItem(String name, String value, String key, int pid) {
    conditionItems.value.add(DomainFilterConditionModel("$name: $value", key));
  }

  /// 格式化范围值
  String _formatRangeValue(String min, String max) {
    if (min.isNotEmpty && max.isNotEmpty) {
      return '$min-$max';
    } else if (min.isNotEmpty) {
      return '≥$min';
    } else if (max.isNotEmpty) {
      return '≤$max';
    }
    return '';
  }

  // MARK: - 数据处理方法

  /// 通过filterData更新sections和conditionItems
  void _updateSectionAndConditionByFilterData(String currentKey) {
    conditionItems.value = [];

    for (var section in sections.value) {
      for (var item in section.children) {
        // 更新常规item
        updateItemValue(item, currentKey);

        // 更新衍生item值
        for (var derivativeItem in item.derivativeItems) {
          updateItemValue(derivativeItem, currentKey);
        }

        // 更新条件展示项
        updateConditionItem(item, currentKey);
      }
      section.hasCondition = conditionItems.value.any(
        (condition) =>
            section.children.any((item) => item.key == condition.key),
      );
    }
    // 刷新数据
    sections.refresh();
  }

  /// 通过filterData获取filterItems
  void updateConditionItem(DomainFilterItemModel item, String currentKey) {
    switch (item.type) {
      case DomainFilterItemType.singleChoice:
        _handleSingleChoiceCondition(item);
        break;
      case DomainFilterItemType.multipleChoice:
        _handleMultipleChoiceCondition(item);
        break;
      case DomainFilterItemType.singleInput:
        _handleSingleInputCondition(item);
        break;
      case DomainFilterItemType.doubleInput:
        // 双输入框(为衍生条目，依赖父级)，无需处理
        break;
      case DomainFilterItemType.singleChoiceWithInput:
        _handleSingleChoiceWithInputCondition(item, currentKey);
        break;
      case DomainFilterItemType.groupSingleChoice:
        _handleGroupSingleChoiceCondition(item);
        break;
      case DomainFilterItemType.doublePicker:
        _handleDoublePickerCondition(item);
        break;
    }
  }

  /// 更新item内容
  void updateItemValue(DomainFilterItemModel item, String currentKey) {
    switch (item.type) {
      case DomainFilterItemType.singleChoice:
        _updateSingleChoiceValue(item);
        break;
      case DomainFilterItemType.multipleChoice:
        _updateMultipleChoiceValue(item);
        break;
      case DomainFilterItemType.singleInput:
        _updateSingleInputValue(item, currentKey.isEmpty);
        break;
      case DomainFilterItemType.singleChoiceWithInput:
        _updateSingleChoiceWithInputValue(item, currentKey);
        break;
      case DomainFilterItemType.doubleInput:
        _updateDoubleInputValue(item);
        break;
      case DomainFilterItemType.groupSingleChoice:
        _updateGroupSingleChoiceValue(item);
        break;
      case DomainFilterItemType.doublePicker:
        _updateDoublePickerValue(item);
        break;
    }
  }

  // MARK: - condition分类处理

  /// 处理单选条件
  void _handleSingleChoiceCondition(DomainFilterItemModel item) {
    if (item.options.isEmpty) return;

    for (var option in item.options) {
      if (!option.isSelected) continue;

      if (option.value == item.derivativeValue) {
        // 衍生选项
        bool hasValue = _hasDerivativeItemValue(item.derivativeItems);
        if (hasValue) {
          _addConditionItem(item.name, option.name, item.key, item.pid);
        }
      } else if (option.value.isNotEmpty) {
        // 普通选项
        _addConditionItem(item.name, option.name, item.key, item.pid);
      }
    }
  }

  /// 检查衍生项是否有值
  bool _hasDerivativeItemValue(List<DomainFilterItemModel> items) {
    for (var item in items) {
      // 检查选项
      if (item.options.any((option) => option.isSelected)) {
        return true;
      }
      // 检查输入框
      if (item.inputValue1.isNotEmpty || item.inputValue2.isNotEmpty) {
        return true;
      }
    }
    return false;
  }

  /// 处理多选条件
  void _handleMultipleChoiceCondition(DomainFilterItemModel item) {
    if (item.options.isEmpty) return;

    List<String> selectedOptions = [];
    for (var option in item.options) {
      if (option.isSelected && option.value.isNotEmpty) {
        selectedOptions.add(option.name);
      }
    }

    if (selectedOptions.isNotEmpty) {
      String valueString = selectedOptions.join('、');
      _addConditionItem(item.name, valueString, item.key, item.pid);
    }
  }

  /// 处理单输入框带复选框条件
  void _handleSingleInputCondition(DomainFilterItemModel item) {
    if (item.value.isEmpty) return;

    String valueString = "“${item.value}”";

    if (item.options.isNotEmpty) {
      List<String> selectedOptions = [];
      for (var option in item.options) {
        if (option.isSelected) {
          selectedOptions.add(option.name);
        }
      }

      if (selectedOptions.isNotEmpty) {
        valueString += selectedOptions.join('、');
      }
    }

    _addConditionItem(item.name, valueString, item.key, item.pid);
  }

  /// 处理单选带双输入框条件
  void _handleSingleChoiceWithInputCondition(
    DomainFilterItemModel item,
    String currentKey,
  ) {
    // 处理选项
    for (var option in item.options) {
      if (option.isSelected &&
          option.value.isNotEmpty &&
          currentKey != item.inputKey1 &&
          currentKey != item.inputKey2) {
        _addConditionItem(item.name, option.name, item.key, item.pid);
      }
    }

    // 输入框
    if (currentKey == item.key) return;

    String valueString = _formatRangeValue(item.inputValue1, item.inputValue2);
    if (valueString.isNotEmpty) {
      _addConditionItem(item.name, "\"$valueString\"", item.key, item.pid);
    }
  }

  /// 处理单选群组条件
  void _handleGroupSingleChoiceCondition(DomainFilterItemModel item) {
    if (item.groupItems.isEmpty) return;

    for (var group in item.groupItems) {
      for (var option in group.options) {
        if (option.isSelected && option.value.isNotEmpty) {
          _addConditionItem(item.name, option.name, item.key, item.pid);
        }
      }
    }
  }

  /// 处理双选择器条件
  void _handleDoublePickerCondition(DomainFilterItemModel item) {
    String valueString = _formatRangeValue(item.inputValue1, item.inputValue2);
    if (valueString.isNotEmpty) {
      _addConditionItem(item.name, valueString, item.key, item.pid);
    }
  }

  // MARK: - sectionItem分类处理

  /// 更新单选值
  void _updateSingleChoiceValue(DomainFilterItemModel item) {
    for (var option in item.options) {
      bool isSelected = option.value == filterData.value[item.key];
      option.isSelected = isSelected;

      // 如果选中非衍生选项，清除衍生项内容
      if (isSelected && option.value != item.derivativeValue) {
        _clearDerivativeItems(item.derivativeItems);
      }
    }
  }

  /// 清除衍生项内容
  void _clearDerivativeItems(List<DomainFilterItemModel> items) {
    for (var item in items) {
      _removeRelatedKeys(item.key);
      item.inputValue1 = '';
      item.inputValue2 = '';
      for (var option in item.options) {
        option.isSelected = false;
      }
    }
  }

  /// 更新多选值
  void _updateMultipleChoiceValue(DomainFilterItemModel item) {
    List<String> values = [];
    if (filterData.value[item.key] != null) {
      values = (filterData.value[item.key] as String).split(',');
    }

    for (var option in item.options) {
      option.isSelected = values.contains(option.value);
    }
  }

  /// 更新单输入框带复选框值
  void _updateSingleInputValue(DomainFilterItemModel item, bool isClear) {
    // 输入框
    if (isClear) {
      filterData.value.remove(item.key);
    }
    item.value = filterData.value[item.key] ?? '';

    // 复选框
    for (var option in item.options) {
      if (isClear) {
        filterData.value.remove(option.key);
      }
      option.isSelected = filterData.value[option.key] == '1';
    }
  }

  /// 更新单选带双输入框值
  void _updateSingleChoiceWithInputValue(
    DomainFilterItemModel item,
    String currentKey,
  ) {
    // 单选
    for (var option in item.options) {
      bool isSelected = option.value == filterData.value[item.key];
      option.isSelected = isSelected;

      // 如果选中选项且当前操作不是输入框相关，清除输入框
      if (isSelected &&
          currentKey != item.inputKey1 &&
          currentKey != item.inputKey2) {
        filterData.value.remove(item.inputKey1);
        filterData.value.remove(item.inputKey2);
        item.inputValue1 = '';
        item.inputValue2 = '';
      }
    }

    // 双输入框
    item.inputValue1 = filterData.value[item.inputKey1] ?? '';
    item.inputValue2 = filterData.value[item.inputKey2] ?? '';

    // 如果有输入框值且当前操作不是选项相关，清除选项
    if ((item.inputValue1.isNotEmpty || item.inputValue2.isNotEmpty) &&
        currentKey != item.key) {
      for (var option in item.options) {
        option.isSelected = false;
      }
      filterData.value.remove(item.key);
    }
  }

  /// 更新双输入框值
  void _updateDoubleInputValue(DomainFilterItemModel item) {
    item.inputValue1 = filterData.value[item.inputKey1] ?? '';
    item.inputValue2 = filterData.value[item.inputKey2] ?? '';
  }

  /// 更新单选群组值
  void _updateGroupSingleChoiceValue(DomainFilterItemModel item) {
    for (var group in item.groupItems) {
      for (var option in group.options) {
        option.isSelected = option.value == filterData.value[item.key];
      }
    }
  }

  /// 更新双选择器值
  void _updateDoublePickerValue(DomainFilterItemModel item) {
    item.inputValue1 = filterData.value[item.inputKey1] ?? '';
    item.inputValue2 = filterData.value[item.inputKey2] ?? '';
  }

  // MARK: - 数据初始化

  /// 获取数据
  Future<void> _getSections() async {
    sections.value = await DomainAction.fetchFilterSectionList();
    _addRegisterAndDeleteTimeOptions();
  }

  /// 手动添加注册时间和删除时间的选项
  void _addRegisterAndDeleteTimeOptions() {
    final timeSection = sections.value.firstWhere(
      (section) => section.key == 'sjlx',
    );

    _addRegisterTimeOptions(timeSection);
    _addDeleteTimeOptions(timeSection);
  }

  /// 添加注册时间选项
  void _addRegisterTimeOptions(DomainFilterSectionModel timeSection) {
    final registerTimeItem = timeSection.children.firstWhere(
      (item) => item.key == 'zcsj',
    );

    // 添加"不限"选项
    registerTimeItem.options.add(buildOptionModel(0, '不限', ''));

    // 添加年份选项
    final currentYear = DateTime.now().year;
    final years = List.generate(19, (index) => currentYear - 1 - index);

    registerTimeItem.options.addAll(
      years.map((year) => buildOptionModel(year, '≤$year年', year.toString())),
    );
  }

  /// 添加删除时间选项
  void _addDeleteTimeOptions(DomainFilterSectionModel timeSection) {
    final deleteTimeItem = timeSection.children.firstWhere(
      (item) => item.key == 'scsj',
    );

    // 添加基本选项
    deleteTimeItem.options.add(buildOptionModel(0, '不限', ''));
    deleteTimeItem.options.add(buildOptionModel(1, '[所有]待删除(可预定)', '1'));

    // 添加未来7天的日期
    final currentDate = DateTime.now();
    for (int i = 0; i <= 7; i++) {
      final date = currentDate.add(Duration(days: i));
      final dateString = date.toIso8601String().substring(0, 10);
      deleteTimeItem.options.add(
        buildOptionModel(i + 10, dateString, dateString),
      );
    }

    // 添加已删除选项
    deleteTimeItem.options.add(buildOptionModel(2, '[所有]已删除(未注册)', '2'));

    // 添加过去6天的日期
    for (int i = 1; i <= 6; i++) {
      final date = currentDate.subtract(Duration(days: i));
      final dateString = date.toIso8601String().substring(0, 10);
      deleteTimeItem.options.add(
        buildOptionModel(i + 100, dateString, dateString),
      );
    }

    // 添加自定义选项
    _addCustomDeleteTimeOption(deleteTimeItem, currentDate);
  }

  /// 添加自定义删除时间选项
  void _addCustomDeleteTimeOption(
    DomainFilterItemModel deleteTimeItem,
    DateTime currentDate,
  ) {
    var customOption = DomainFilterOptionModel.fromJson({
      "id": 3,
      "name": "自定义",
      "value": "3",
    });

    var customItem = DomainFilterItemModel.fromJson({
      "name": "自定义",
      "key": "scsj_m",
      "type": "m_choice",
    });

    // 添加过去6天的日期
    for (int i = 6; i >= 1; i--) {
      final date = currentDate.subtract(Duration(days: i));
      final dateString = date.toIso8601String().substring(0, 10);
      customItem.options.add(buildOptionModel(i + 100, dateString, dateString));
    }

    // 添加未来7天的日期
    for (int i = 0; i <= 7; i++) {
      final date = currentDate.add(Duration(days: i));
      final dateString = date.toIso8601String().substring(0, 10);
      customItem.options.add(buildOptionModel(i + 10, dateString, dateString));
    }

    deleteTimeItem.derivativeValue = '3';
    deleteTimeItem.derivativeItems.add(customItem);
    deleteTimeItem.options.add(customOption);
  }

  /// 构造选项模型
  DomainFilterOptionModel buildOptionModel(int id, String name, String value) {
    return DomainFilterOptionModel(id, name, value, '', false);
  }
}
